
package com.it.myd.filter;

import com.it.myd.bean.main.User;
import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

@WebFilter(urlPatterns = "/*")
public class SuperFilter implements Filter {
    private static final Logger logger = LoggerFactory.getLogger(SuperFilter.class);
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        // 初始化过滤器
        System.out.println("|-_-| SUPER过滤器启动!");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        String requestURI = httpRequest.getRequestURI();

        if (isFileOrImageRequest(requestURI)) {
        }else{
            if(isMainRequest(requestURI)){
                HttpSession session = httpRequest.getSession(false); // 不创建新的会话
                if (session == null) {
                    logger.warn("|O O| 会话不存在，无法获取用户信息!");
                    httpResponse.sendRedirect("../gologin");
                    return;
                }

                User user = (User) session.getAttribute("user");
                if (user == null) {
                    logger.warn("|O O| 检测到未登录请求!");
                    httpResponse.sendRedirect("../gologin");
                    return;
                }
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁过滤器
        System.out.println("|x_x| SUPER过滤器燃尽!");
    }

    private boolean isFileOrImageRequest(String requestURI) {
        // 检查请求的扩展名是否为图片或文件类型
        return requestURI.endsWith(".jpg") ||
                requestURI.endsWith(".jpeg") ||
                requestURI.endsWith(".png") ||
                requestURI.endsWith(".gif") ||
                requestURI.endsWith(".pdf") ||
                requestURI.endsWith(".doc") ||
                requestURI.endsWith(".docx") ||
                requestURI.endsWith(".xls") ||
                requestURI.endsWith(".xlsx");
    }

    private boolean isMainRequest(String requestURI) {
        return (requestURI.contains("/jump")&&!requestURI.contains("gologin")) ||
                requestURI.endsWith("/module");
    }
}